package com.song.ResourceNode.client;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.InetSocketAddress;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.collections.CollectionUtils;

import com.song.corebean.PackageMessage;

public class NodeClientHandler extends ChannelInboundHandlerAdapter{

	private BlockingQueue<PackageMessage> queue = new LinkedBlockingQueue<PackageMessage>();


	public PackageMessage readMsg() {
		return this.queue.poll();
	}
	
	public boolean isEmpQueue()
	{
		return CollectionUtils.isEmpty(queue);
	}

	public PackageMessage msg;
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		PackageMessage tmpmsg = (PackageMessage) msg;
		this.queue.add(tmpmsg);
	}

	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); 
	}

	
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		
		InetSocketAddress addr = (InetSocketAddress)ctx.channel().remoteAddress();
		
//		ctx.writeAndFlush(addr.getHostName()+":"+addr.getPort());
		
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}
	
}
